import { Component, OnInit, Output, Input, EventEmitter, ViewChild, TemplateRef } from '@angular/core';
import { FormBasicService, DesignerEnvType } from '@farris/designer-services';
// import { DomService } from '../../../../service/dom.service';
import { NotifyService } from '@farris/ui-notify';
import { DatagridComponent } from '@farris/ui-datagrid';
// import { DeclarationCommand } from '../../../../entity/dom-entity';
// import { DgControlType } from '../../../../components/dg-control-type';
import { ModalOptions } from '@farris/ui-modal';
import { HttpClient } from '@angular/common/http';


// TODO: 重构成DynamicDropdown。配置一个动态数据源（restful api）和取值字段、显示字段。
//  支持搜索（或远程搜索），支持弹出窗口选择。
//  选择轻应用其实是传入获取轻应用数据的api，下拉选择。

@Component({
  selector: 'app-select-microapp',
  templateUrl: './select-microapp.component.html',
  styleUrls: ['./select-microapp.component.css']
})
export class SelectMicroAppComponent implements OnInit {

  @ViewChild('microAppList') microAppList: DatagridComponent

  @ViewChild('selectMicroAppFooter') modalFooter: TemplateRef<any>;

  @Input() value;

  @Input() editorParams = {};

  modalConfig: ModalOptions = {
    title: '选择关联轻应用',
    width: 855,
    height: 550,
    showButtons: true
  };
  
  // 模态框关闭
  @Output() closeModal = new EventEmitter<any>();

  // 模态框确定后关闭，并传递参数
  @Output() submitModal = new EventEmitter<any>();

  // 当前环境是否零代码
  isNocodeEnv = true;

  private getMicroAppUrl = '/api/dev/nocode/v1.0/micro-apps';

  relatedMicroApp: any[] = [];

  microAppDataCols = [
    { field: 'appId', title: 'ID', visible: false},
    { field: 'appCode', title: '编号', align: 'center', halign: 'center' },
    { field: 'appName', title: '名称', align: 'center', halign: 'center' },
    { field: 'taskCategoryId', title: '任务分类id', visible: false}
  ];

  microAppListData: any[] = [];

  constructor(
    private formBasicService: FormBasicService,
    // private domService: DomService,
    private notifyService: NotifyService,
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.isNocodeEnv = this.formBasicService.envType === DesignerEnvType.noCode;
    this.getMicroApp().subscribe((res: any[]) => {
      if(res && res.length) {
        const microAppWithWorkFlow = res.filter(data => !!data.processCategory);
        microAppWithWorkFlow.forEach(app => {
          let microAppData = Object.assign({}, {
            appId: app.id,
            appCode: app.code,
            appName: app.name,
            taskCategoryId: app.processCategory
          });
          this.microAppListData.push(microAppData);
        });
      }
    });
  }

  private getMicroApp() {
    return this.http.get(`${this.getMicroAppUrl}`);
  }

  onChecked(e: any) {
    this.relatedMicroApp.push(e.data);
  }

  onUnChecked(e: any) {
    const index = this.relatedMicroApp.findIndex(app => app.appId == e.id);
    this.relatedMicroApp.splice(index, 1);
    this.relatedMicroApp = this.relatedMicroApp.slice();
  }

  clickConfirm() {
    if(this.relatedMicroApp.length == 0) {
      this.submitModal.emit({ value: '' });
      return;
    }
    const relatedMicroAppNameArr = this.relatedMicroApp.map(app => { return app.appName }); 
    const taskCategoryIdArr = this.relatedMicroApp.map(app => { return app.taskCategoryId });
    this.submitModal.emit({value: taskCategoryIdArr.join(',')});
  }

  clickCancel() {
    this.closeModal.emit();
  }
}
